package com.uujava.minibox.ui.tree;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JToolTip;

import com.android.ninepatch.NinePatch;

/**
 * 功能: 代替原来的JToolTip 增加了背景图片
 * 
 * @author k 2013年7月30日11:29:47
 * 
 */
public class ShowAppToolTip extends JToolTip {
	private static final long serialVersionUID = 1L;

	private NinePatch mPatch = null;// NinePatch作为全局对象，提高性能
	private JLabel lab = new JLabel();

	public ShowAppToolTip() {
		super();
		setLayout(new BorderLayout());
		this.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));//设置上下左右各空出20px
		add(lab);

	}

	public void setTipText(String tipText) {
		if (lab != null)
			lab.setText(tipText);
		else
			lab = new JLabel(tipText);
	}

	public void setPatch(InputStream stream, Boolean is9Patch, Boolean convert) {

		try {// *** 关键代码：读取9格图 START
			mPatch = NinePatch.load(stream, is9Patch, convert);
		} catch (IOException e) {
			print("ToolIip获取背景图片出错");
			e.printStackTrace();
		}
	}

	public void setPatch(URL fileUrl, Boolean convert) {
		try {// *** 关键代码：读取9格图 START
			mPatch = NinePatch.load(fileUrl, convert);
		} catch (IOException e) {
			print("ToolIip获取背景图片出错");
			e.printStackTrace();
		}
	}

	private void print(String str) {
		System.out.println(str);
	}

	public Dimension getPreferredSize() {
		return new Dimension(200, 100);
	}

	/**
	 * 重写父类方法，以便实现自定义背景的绘制.
	 */
	@Override
	protected void paintComponent(Graphics g) {
		Graphics2D g2 = (Graphics2D) g;
		Rectangle clip = g2.getClipBounds();

		// *** 关键代码：使用9格图 START
		// 使用9格图绘制面板的背景
		if (mPatch != null)
			mPatch.draw(g2, clip.x, clip.y, clip.width, clip.height);
		// *** 关键代码：使用9格图 END
	}

}